#include "https.h"
#include <iostream>


Https::Https()
{
    curl_global_init(CURL_GLOBAL_DEFAULT);
    curl = curl_easy_init();
}
Https::~Https()
{
    curl_easy_cleanup(curl);
    curl_global_cleanup();
}

void Https::Show(std::string url)
{
    curl_global_init(CURL_GLOBAL_DEFAULT);
    if(curl) 
    {
        curl_easy_setopt(curl, CURLOPT_URL, "https://example.com/");
#ifdef SKIP_PEER_VERIFICATION
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
#endif
#ifdef SKIP_HOSTNAME_VERIFICATION
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
#endif

        CURLcode  res = curl_easy_perform(curl);
        if(res != CURLE_OK)
            fprintf(stderr, "curl_easy_perform() failed: %s\n",curl_easy_strerror(res));

    }

    curl_global_cleanup();
}
CURLcode Https::HttpPost(const std::string & strUrl, std::string szJson,std::string & strResponse,int nTimeout)
{
    CURLcode res;
    char szJsonData[1024];
    memset(szJsonData, 0, sizeof(szJsonData));
    strcpy(szJsonData, szJson.c_str());
    struct curl_slist* headers = NULL;
    if (curl == NULL) {
        return CURLE_FAILED_INIT;
    }

    CURLcode ret;
    ret = curl_easy_setopt(curl, CURLOPT_URL, strUrl.c_str());
    //    std::cout << ret << std::endl;

    std::string strJsonData;
    strJsonData = "queryWord=CONTENT:码农&";
    strJsonData += "startTime=1507605327&" ;
    strJsonData += "endTime=1508210127&" ;
    strJsonData += "maxCount=500&" ;
    strJsonData += "contextLength=200" ;

    ret = curl_easy_setopt(curl, CURLOPT_POSTFIELDS, strJsonData);
    //curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
    ret = curl_easy_setopt(curl, CURLOPT_TIMEOUT, nTimeout);

    ret = curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, Https::receive_data);

    ret = curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void*)&strResponse);

    res = curl_easy_perform(curl);
    return res;
}
size_t Https::receive_data(void *contents, size_t size, size_t nmemb, void *stream)
{
    std::string *str = (std::string*)stream;
    (*str).append((char*)contents, size*nmemb);
    return size * nmemb;
}

